#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "parse.h"

void parse_cmd(char *line, struct cmd *cmd)
{
	char *temp;
	temp = (char *)malloc(sizeof(line));
	strcpy(temp, line);
	//printf("%s\n" , temp);
	char *word = strtok(temp, " ");
	char *p = NULL, *q = NULL;
	while (word != NULL) {
		p = strchr(word, '<');
		q = strchr(word, '>');
		if (p) {
			cmd->input = (char *)malloc(sizeof(word));
			strcpy(cmd->input, p+1);	
		} else if (q) {
			cmd->output = (char *)malloc(sizeof(word));
			strcpy(cmd->output, q+1);
		} else {
			cmd->argv[cmd->argc] = (char *)malloc(sizeof(word));
			//printf("%s\n", word);
			strcpy(cmd->argv[cmd->argc], word); 
			cmd->argc++;
		}	
		if (cmd->argc >= MAX_ARGC) {
			fprintf(stderr, "too many arguments\n");
			exit(0);
		}
		word = strtok(NULL, " ");
	}
	free(temp);
	cmd->argv[cmd->argc] = NULL;		
}

void dump_cmd(struct cmd *cmd)
{
	printf("argc = %d\n", cmd->argc);
	
	printf("argv = {");
	int i;
	for (i = 0; i < cmd->argc; ++i) 
		printf("%s ", cmd->argv[i]);
	printf("}\n");
	
	if (cmd->input == NULL) 
		printf("input = NULL\n");
	else
		printf("input = %s\n", cmd->input);
	
	if (cmd->output == NULL) 
		printf("output = NULL\n");
	else
		printf("output = %s\n", cmd->output);
	//printf("\n");
}

int parse_pipe_cmd(char *line, struct cmd *cmdv)
{
	char *save;
	//char *temp = (char *)malloc(sizeof(line)+1);
	//strcpy(temp, line);
	//printf("%s\n",temp);
	char *part = strtok_r(line, "|", &save);
	int cmdc=0;
	while (part != NULL) {
		parse_cmd(part, cmdv+cmdc);
		part = strtok_r(NULL, "|", &save);
		cmdc++;
	}
	//free(temp);
    return cmdc;
}

void dump_pipe_cmd(int cmdc, struct cmd *cmdv)
{
    int i;

    printf("pipe cmd, cmdc = %d\n", cmdc);
    for (i = 0; i < cmdc; i++) {
        struct cmd *cmd = cmdv + i;
        dump_cmd(cmd);
    }
}
